package com.table;

import com.appclient.DaoInstanceEnum;
import com.carpark.ejb.Model.TarrifsModel;
import com.wizardOther.Items.ValidationForm;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

/**
 *
 * @author Vi
 */
public class TariffTableController extends ValidationForm{

    @FXML
    private TextField filterField;
    @FXML
    private TableView<TarrifsModel> tariffTable;
    @FXML
    private TableColumn<TarrifsModel, String> name;
    @FXML
    private TableColumn<TarrifsModel, String> startDate;
    @FXML
    private TableColumn<TarrifsModel, String> endDate;
    @FXML
    private TableColumn<TarrifsModel, String> time;
    @FXML
    private TableColumn<TarrifsModel, String> rank;
    @FXML
    private TableColumn<TarrifsModel, String> carType;
    @FXML
    private TableColumn<TarrifsModel, String> comment;
    @FXML
    private Button choose;
    private ObservableList<TarrifsModel> masterData = FXCollections.observableArrayList();
    private ObservableList<TarrifsModel> filteredData = FXCollections.observableArrayList();
    private Stage dialogStage;
    private Integer selectedTariff;

    public Integer getSelectedTariff() {
        return selectedTariff;
    }


    public TariffTableController() {
        List<TarrifsModel> data = DaoInstanceEnum.INSTANCE.getDao().getAllTarrifs();
        for (TarrifsModel tariff : data) {
            tariff.setCarType(renameCarTypeToPolish(tariff.getCarType()));
            tariff.setIssueDate(Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(tariff.getIssueDate())));
            tariff.setEndDate(Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(tariff.getEndDate())));
            masterData.add(tariff);
        }

        filteredData.addAll(masterData);
        masterData.addListener(new ListChangeListener<TarrifsModel>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends TarrifsModel> change) {
                updateFilteredData();
            }
        });
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        name.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("Name"));
        startDate.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("IssueDate"));
        endDate.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("EndDate"));
        time.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("DurationTime"));
        rank.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("Rank"));
        carType.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("CarType"));
        comment.setCellValueFactory(
                new PropertyValueFactory<TarrifsModel, String>("Comments"));

        tariffTable.setItems(filteredData);

        filterField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                updateFilteredData();
            }
        });
    }

    /**
     * Updates the filteredData to contain all data from the masterData that
     * matches the current filter.
     */
    private void updateFilteredData() {
        filteredData.clear();

        for (TarrifsModel p : masterData) {
            if (matchesFilter(p)) {
                filteredData.add(p);
            }
        }

        // Must re-sort table after items changed
        reapplyTableSortOrder();
    }

    /**
     * Returns true if the person matches the current filter. Lower/Upper case
     * is ignored.
     *
     * @param car
     * @return
     */
    private boolean matchesFilter(TarrifsModel tarrif) {
        String filterString = filterField.getText();
        if (filterString == null || filterString.isEmpty()) {
            return true;
        }
        String lowerCaseFilterString = filterString.toLowerCase();

        if (tarrif.getName().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (tarrif.getIssueDate().toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (tarrif.getEndDate().toString().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (tarrif.getDurationTime().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if ((String.valueOf(tarrif.getRank())).toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (tarrif.getCarType().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
          if(tarrif.getComments()!=null){
        if (tarrif.getComments().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
         }

        return false;
    }

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    private void reapplyTableSortOrder() {
        ArrayList<TableColumn<TarrifsModel, ?>> sortOrder = new ArrayList<>(tariffTable.getSortOrder());
        tariffTable.getSortOrder().clear();
        tariffTable.getSortOrder().addAll(sortOrder);
    }

    @FXML
    private void makeChoice(ActionEvent event) {
        if (event.getSource() == choose) {
            try{
                selectedTariff = tariffTable.getSelectionModel().getSelectedItem().getTarrifId();
            }
            catch(Exception e){
                 createPopup("Zaznacz najpierw w tabeli pojazd!");
            }
            if (selectedTariff != null) {
                dialogStage.close();
            }
        }
    }

   
}
